﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

using RexToy.Configuration;

namespace Monitor.Core
{
    public class DataWriter
    {
        private const string MONGO = "mongo";
        private const string MONITOR = "monitor";
        private const string HISTORY = "history";
        private const string LATEST = "latest";
        private const string ERROR = "error";

        private MongoDatabase _db;

        public DataWriter()
        {
            var cnnstr = AppConfig.Config.ReadValue(MONGO, MONITOR);
            MongoClient c = new MongoClient(cnnstr);
            var svr = c.GetServer();
            _db = svr.GetDatabase(MONITOR);
        }

        public void Write(ISensor s)
        {
            WriteHistory(s);
            WriteLatest(s);
        }

        private void WriteHistory(ISensor s)
        {
            BsonDocument doc = new BsonDocument();
            doc["sid"] = s.Id;
            doc["description"] = s.Description;
            doc["status"] = s.Status.ToString();
            doc["time"] = s.LastRefreshTime;
            if (s.Status != ServiceStatus.Alive)
                doc["detail"] = s.LastError;

            var history = _db.GetCollection(HISTORY);
            history.Insert(doc);
        }

        private void WriteLatest(ISensor s)
        {
            BsonDocument doc = new BsonDocument();
            doc["_id"] = s.Id;
            doc["sid"] = s.Id;
            doc["description"] = s.Description;
            doc["status"] = s.Status.ToString();
            doc["time"] = s.LastRefreshTime;
            doc["detail"] = s.LastError;

            var latest = _db.GetCollection(LATEST);
            var result = latest.Save(doc);
        }
    }
}
